It is rarely useful to declare a function at block scope. Such a function will not get special access to any name in its enclosing scope, and
therefore, it is equivalent but clearer to declare it instead in the enclosing namespace.
Additionally, when a function is declared at block scope, the intent is often not to declare a function but instead to declare and initialize a
variable. This problem is nicknamed the most vexing parse and stems from the fact that some syntaxes can be ambiguous, and that in that case
the language unintuitively favors function declaration:
void f() {
int a;
string b();
short c(short (a));
}
-
b
could be interpreted as:
- A variable of type
string
with empty initialization or
- A function with no argument and returning a
string
.
The second interpretation is selected.
- Similarly,
c
could be interpreted as:
- A variable of type
short
initialized with the value a
converted to short
or
- A function that takes a parameter named
a
(with extra parentheses) of type short
and returning a
short
Here again, the second interpretation is selected.
There are several ways to write the code differently so that b
and c
can only be interpreted as variables. For
instance:
void f() {
int a;
string b {};
auto c = short (a);
}
By raising issues on local function declaration, this rule helps detect when a function is inadvertently declared.